//
//  CLCaseNoteController.m
//  CareLink
//
//  Created by tanky on 16/8/18.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLCaseNoteController.h"
#import "CLCasesTableView.h"
#import "CLCasesTableViewCell.h"
#import "CLAddCaseTableViewController.h"
#import "CLCaseDisplayController.h"
#import "MJRefresh.h"
#import "CLPersonalInfo.h"
#import "CLDataManager.h"
#import "CLDataModel.h"

@interface CLCaseNoteController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet CLCasesTableView *casesTableView;
@property(nonatomic,strong)CLPersonalInfo *personalInfo;
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UILabel *nameGender;
@property (weak, nonatomic) IBOutlet UILabel *IDNum;
@property (weak, nonatomic) IBOutlet UILabel *phoneNum;
@property(nonatomic,strong) NSArray *caseArray;

@end

@implementation CLCaseNoteController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self readData];
    [self setupUI];
    [self loadPersonalInfo];
}

- (void)viewWillAppear:(BOOL)animated{
    if (self.deleteDict) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:self.caseArray];
        [mArr removeObject:self.deleteDict];
        self.caseArray = mArr;
        [self.casesTableView reloadData];
        self.deleteDict = nil;
    }
    if (self.saveDict) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:self.caseArray];
        [mArr addObject:self.saveDict];
        self.caseArray = mArr;
        [self.casesTableView reloadData];
        self.saveDict = nil;
    }
}

//读取数据数据
- (void)readData{
    CLDataManager *dataManager = [CLDataManager sharedManager];
    NSMutableArray *mArr = [NSMutableArray new];
    for (CLDataModel *dataModel in dataManager.dataArr) {
        NSMutableDictionary *dict = [NSMutableDictionary new];
        [dict setObject:dataModel.diseaseTypeparameter forKey:@"diseaseTypeparameter"];
        NSLog(@"%@",dataModel.diseaseDetail);
        if (dataModel.diseaseDetail) {
            [dict setObject:dataModel.diseaseDetail forKey:@"diseaseDetail"];
        }else{
            [dict setObject:dataModel.diseaseTypeparameter forKey:@"diseaseDetail"];
        }
        [dict setObject:dataModel.symptomDes forKey:@"symptomDes"];
        [dict setObject:dataModel.time forKey:@"time"];
        [mArr addObject:dict];
        if (dataModel.image) {
            [dict setObject:dataModel.image forKey:@"image"];
        }
    }
    NSLog(@"%@",mArr);
    self.caseArray = mArr;
}

//控制器销毁的时候保存数据
- (void)dealloc{
    CLDataManager *dataManager = [CLDataManager sharedManager];
    NSMutableArray *mArr = [NSMutableArray new];
    NSLog(@"%@",self.caseArray); 
    for (NSDictionary *dict in self.caseArray) {
        CLDataModel *dataModel = [CLDataModel new];
        
        CLData *data = [CLData new];
        [data setValuesForKeysWithDictionary:dict];
        [mArr addObject:dataModel];
        NSLog(@"%zd",self.caseArray.count);
        NSLog(@"%@",dict);
    }
    dataManager.dataArr = mArr;
//
}

- (void)loadPersonalInfo{
    NSString *url = @"http://iosapi.itcast.cn/carelinkQuickLogin.json.php";
    NSDictionary *paramDic = @{@"login_token":@"985c96ce43bb5ef69de3e1ad8afaa83f",@"user_id":@(11),@"true_name":@"test",@"card_number":@"111",@"card_type":@(11)};
    CLNetworkManager4JSON *netManager = [CLNetworkManager4JSON sharedManager];
    __weak typeof(self) weakSelf = self;
    [netManager POST:url parameters:paramDic success:^(NSDictionary *jsonData, NSString *msg) {
        weakSelf.personalInfo = [CLPersonalInfo yy_modelWithDictionary:jsonData];
        weakSelf.nameGender.text = self.personalInfo.true_name;
        weakSelf.IDNum.text = self.personalInfo.card_number;
        weakSelf.phoneNum.text = self.personalInfo.mobile_number;
        NSURL *url = [NSURL URLWithString:self.personalInfo.head_photo];
        [weakSelf.icon sd_setImageWithURL:url];
        weakSelf.icon.image = [UIImage imageNamed:@"patient_defaultphoto_male"];
    }];
}

- (void)setupUI{
    UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = btnItem;
    self.title = @"病例夹";
    if([[[UIDevice currentDevice]systemVersion]floatValue]>=7.0){
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.casesTableView.delegate = self;
    self.casesTableView.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"CLCasesTableViewCell" bundle:nil];
    [self.casesTableView registerNib:nib forCellReuseIdentifier:@"caseNote_id"];
    [self.casesTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //下拉刷新
    __weak typeof(self) weakSelf = self;
    self.casesTableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 结束刷新
            [weakSelf.casesTableView.mj_header endRefreshing];
        });
    }];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y == 0){
        self.casesTableView.bounces = YES;
    }else if(scrollView.contentOffset.y > 0){
        self.casesTableView.bounces = NO;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.caseArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CLCasesTableViewCell *cell = [self.casesTableView dequeueReusableCellWithIdentifier:@"caseNote_id" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *caseDataDict = self.caseArray[indexPath.row];
    if (caseDataDict[@"image"]) {
        cell.casePic.image = caseDataDict[@"image"];
    };
    cell.diseaseType.text = caseDataDict[@"diseaseDetail"];
    cell.diseaseRate.text = caseDataDict[@"symptomDes"];
    cell.timeLabel.text = caseDataDict[@"time"];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 116;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (IBAction)addCase:(UIButton *)sender {
    CLAddCaseTableViewController *addCaseViewController = [CLAddCaseTableViewController new];
    __weak typeof(self) weakSelf = self;
    [addCaseViewController setCaseBlock:^(NSDictionary *addCaseData) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:self.caseArray];
        [mArr addObject:addCaseData];
        weakSelf.caseArray = mArr;
        [weakSelf.casesTableView reloadData];
    }];
    [self showViewController:addCaseViewController sender:nil];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    CLCaseDisplayController *caseDisplayController = [CLCaseDisplayController new];
    caseDisplayController.caseDisplayDict = self.caseArray[indexPath.row];
    
    [self showViewController:caseDisplayController sender:nil];
}


// 获取时间
- (NSString *)loadDate {
    // 这个是NSDate类型的日期，所要获取的年月日都放在这里；
    NSDate *date = [NSDate date];
    
    // 获取当前时间
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    //这句是说你要获取日期的元素有哪些。获取年就要写NSYearCalendarUnit，获取小时就要写NSHourCalendarUnit，中间用|隔开；
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents *d = [cal components:unitFlags fromDate:date];    //把要从date中获取的unitFlags标示的日期元素存放在NSDateComponents类型的d里面；
    //然后就可以从d中获取具体的年月日了；
    NSString *time = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld:%ld", d.year, d.month, d.day, d.hour, d.minute, d.second];
    
    NSLog(@"%@", time);
    return time;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
